#include "libcomm.h"

bool Bitset::IsLittleEndian()
{
	unsigned short a = 0x0102;
	MYLIB_ASSERT(2==sizeof(a));
	unsigned char* b = (unsigned char*)&a;
	return (b[0]==2);
}

template<class T1,class T2>
void common_bitset_get(T1 src, bool low, T2& dst)
{
	int bytes = sizeof(T2);
	bool isLittleEndian = Bitset::IsLittleEndian();
	if((low && !isLittleEndian) || (!low && isLittleEndian))
		src = src >> (bytes*8);
	memcpy(&dst,&src,bytes);
}

template<class T1,class T2>
void common_bitset_make(T1 high, T1 low, T2& dst)
{
	int bytes = sizeof(T1);
	bool isLittleEndian = Bitset::IsLittleEndian();
	if(isLittleEndian)
	{
		dst = ((T2)high << (bytes*8)) | ((T2)low);
	}
	else
	{
		dst = ((T2)low << (bytes*8)) | ((T2)high);
	}
}

unsigned int Bitset::Low(unsigned long long val)
{
	unsigned int ret;
	common_bitset_get(val,true,ret);
	return ret;
}

unsigned int Bitset::High(unsigned long long val)
{
	unsigned int ret;
	common_bitset_get(val,false,ret);
	return ret;
}

unsigned short Bitset::Low(unsigned int val)
{
	unsigned short ret;
	common_bitset_get(val,true,ret);
	return ret;
}

unsigned short Bitset::High(unsigned int val)
{
	unsigned short ret;
	common_bitset_get(val,false,ret);
	return ret;
}

unsigned char Bitset::Low(unsigned short val)
{
	unsigned char ret;
	common_bitset_get(val,true,ret);
	return ret;
}

unsigned char Bitset::High(unsigned short val)
{
	unsigned char ret;
	common_bitset_get(val,false,ret);
	return ret;
}


unsigned long long Bitset::Make(unsigned int high, unsigned int low)
{
	unsigned long long ret;
	common_bitset_make(high,low,ret);
	return ret;
}

unsigned int Bitset::Make(unsigned short high, unsigned short low)
{
	unsigned int ret;
	common_bitset_make(high,low,ret);
	return ret;
}

unsigned short Bitset::Make(unsigned char high, unsigned char low)
{
	unsigned short ret;
	common_bitset_make(high,low,ret);
	return ret;
}